﻿using AntdUI;
using QuestPDF.Fluent;
using Serilog;
using System.ComponentModel;
using System.Diagnostics;
using WorkTool2.Classes.Data;
using WorkTool2.Helpers;

namespace WorkTool2.Controls
{
    public partial class PDFMerge : UserControl
    {
        private Form form;

        public PDFMerge(Form _form)
        {
            form = _form;
            InitializeComponent();
            table.Columns = [
                new Column("Id", "id", ColumnAlign.Center).SetVisible(false),
                new Column("FileName", "文件名称", ColumnAlign.Center).SetWidth("75%"),
                new Column("Action", "操作", ColumnAlign.Center).SetWidth("25%")
            ];
            table.VisibleHeader = false;
        }

        private void uploadDragger_DragChanged(object sender, StringsEventArgs e)
        {
            TableBindData([.. e.Value]);
        }

        private void merge_btn_Click(object sender, EventArgs e)
        {
            Spin.open(form, "正在处理中，请耐心等候...",
                config =>
                {
                    try
                    {
                        if (_tableList.Count > 1)
                        {
                            var pdf = DocumentOperation
                            .LoadFile(_tableList[0].FilePath);
                            for (int i = 1; i < _tableList.Count; i++)
                            {
                                pdf.MergeFile(_tableList[i].FilePath);
                            }
                            var filePath = Path.Combine(SettingsHelper._fileSettings.SaveFolder, $"Merge-{DateTime.Now:yyyyMMddHHmmss}.pdf");
                            pdf.Save(filePath);
                            folder_input.Text = "";
                            _tableList.Clear();
                            if (new Modal.Config(form, "是否打开文件？", $"文件已保存至：{filePath}", TType.Success)
                            {
                                OnButtonStyle = (id, btn) =>
                                {
                                    btn.BackExtend = "135, #6253E1, #04BEFE";
                                },
                                CancelText = "否",
                                OkText = "是"
                            }.open() == DialogResult.OK)
                            {
                                Process.Start(new ProcessStartInfo
                                {
                                    FileName = filePath,
                                    UseShellExecute = true
                                });
                            }
                            (form as Main).AddHistoryData(new HistoryData("合并PDF文档", filePath)).ConfigureAwait(false);
                        }
                        else
                        {
                            Modal.open(form, "提醒", "没有要合并的文档", TType.Warn);
                        }
                    }
                    catch (Exception ex)
                    {
                        Notification.error(form, "合并失败", ex.Message, TAlignFrom.Top);
                        Log.Error(ex, ex.Message);
                    }
                },
                () => { }
            );
        }

        private void table_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            Spin.open(form, "正在处理中，请耐心等候...",
                config =>
                {
                    try
                    {
                        if (e.Record is MergeData data)
                        {
                            if (new Modal.Config(form, "删除提醒", $"是否删除【{data.FileName}】？", TType.Error)
                            {
                                CancelText = "否",
                                OkType = TTypeMini.Primary,
                                OkText = "是",
                            }.open() == DialogResult.OK)
                            {
                                _tableList.Remove(data);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Notification.error(form, "删除失败", ex.Message, TAlignFrom.Top);
                        Log.Error(ex, ex.Message);
                    }
                },
                () => { }
            );
        }

        private void search_btn_Click(object sender, EventArgs e)
        {
            using var folder = new System.Windows.Forms.FolderBrowserDialog();
            if (folder.ShowDialog() == DialogResult.OK)
            {
                Spin.open(form, "正在处理中，请耐心等候...",
                    config =>
                    {
                        try
                        {
                            var folderString = folder.SelectedPath;
                            if (!string.IsNullOrEmpty(folderString))
                            {
                                if (Directory.Exists(folderString))
                                {
                                    var files = Directory.GetFiles(folderString);
                                    var pdfFiles = files.Where(x => Path.GetExtension(x).Equals(".pdf")).ToList();
                                    if (pdfFiles.Count > 1)
                                    {
                                        TableBindData(pdfFiles);
                                        folder_input.Text = folderString;
                                    }
                                    else
                                    {
                                        Modal.open(form, "错误", $"文件夹内{(pdfFiles.Count == 0 ? "未找到.pdf文件" : "只存在一个.pdf文件，无需合并")}，请重新输入！", TType.Error);
                                    }
                                }
                                else
                                {
                                    Modal.open(form, "错误", "文件不存在", TType.Error);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Notification.error(form, "查找文件失败", ex.Message, TAlignFrom.Top);
                            Log.Error(ex, ex.Message);
                        }
                    },
                    () => { }
                );
            }
        }

        private BindingList<MergeData> _tableList = [];

        private void TableBindData(List<string> files)
        {
            foreach (var file in files)
            {
                _tableList.Add(new MergeData(file));
            }
            table.Binding(_tableList);
        }

        private void reset_btn_Click(object sender, EventArgs e)
        {
            folder_input.Text = "";
            _tableList.Clear();
            _tableList.ResetBindings();
        }
    }
}